package com.bijava;

import io.swagger.models.HttpMethod;
import io.swagger.models.Operation;
import io.swagger.models.Path;
import io.swagger.models.Swagger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;
import springfox.documentation.service.Documentation;
import springfox.documentation.spring.web.DocumentationCache;
import springfox.documentation.swagger2.mappers.ServiceModelToSwagger2Mapper;

import java.util.*;

/**
 * @author bijava
 * @version 1.0
 * @since 2020-03-14
 */
@ApiIgnore
@RestController
public class SwaggerScanController {
    @Autowired
    private DocumentationCache documentationCache;
    @Autowired
    private ServiceModelToSwagger2Mapper mapper;

    /**
     * 扫描所有swagger管理的restful接口
     * @return
     */
    @GetMapping("/scan")
    public List<Map<String, Object>> swaggerScan() {
        List<Map<String, Object>> authList = new ArrayList<>();
        Documentation documentation = documentationCache.documentationByGroup("Web端接口服务");
        if (documentation != null) {
            Swagger swagger = mapper.mapDocumentation(documentation);
            Map<String, Path> paths = swagger.getPaths();
            for (Map.Entry<String,Path> entry : paths.entrySet()){
                String pathKey = entry.getKey();
                Path path = entry.getValue();
                Map<HttpMethod, Operation> operationMap = path.getOperationMap();
                for (Map.Entry<HttpMethod,Operation> operationEntry : operationMap.entrySet()){
                    HttpMethod httpMethod = operationEntry.getKey();
                    Operation operation = operationEntry.getValue();
                    List<String> tags = operation.getTags();
                    // 生成返回的map
                    Map<String, Object> auth = new HashMap<>();
                    auth.put("authority", httpMethod.toString().toLowerCase() + ":" + pathKey);
                    auth.put("authorityName", operation.getSummary());
                    auth.put("parentName", tags != null && tags.size() > 0 ? tags.get(0) : null);
                    authList.add(auth);
                }
            }
        }
        return authList;
    }
}
